const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const db = require('./db/main');
const chalk = require('chalk');
const httpLogger = require('./config/log4js').httpLogger;
const router = require('./routes/index');
const permission = require('./config/permission.js') //用户权限验证
var app = express();
// 设置跨域
// app.all('*', function (req, res, next) {
//   res.header('Access-Control-Allow-Origin', '*');
//   res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
//   res.header('Access-Control-Allow-Methods', 'post,get,put,delect,options');
//   if (req.method.toLowerCase() == 'options')
//     res.sendStatus(200); 
//   else
//     next();
// });
// 添加json解析
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(express.static(path.join(__dirname, 'public')));
// 日志打印
app.use(httpLogger);
// 权限验证
app.use(permission)
router(app);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  res.sendStatus(404);
});
var debug = require('debug')('my-application'); // debug模块
app.set('port',9090); // 设定监听端口
//启动监听
var server = app.listen(app.get('port'), function () {
  console.log(
    chalk.green(`${app.get('port')}端口启动`)
  );
  debug('Express server listening on port ' + server.address().port);
});